package net.xdclass.intercepto;


import io.jsonwebtoken.Claims;
import net.xdclass.enums.BizCodeEnum;
import net.xdclass.model.LoginUser;
import net.xdclass.utils.CommonUtil;
import net.xdclass.utils.JWTUtil;
import net.xdclass.utils.JsonData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {
    public static ThreadLocal<LoginUser> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");
        if (token==null){
            token=request.getParameter("token");
        }
        if (StringUtils.isNotBlank(token)){
            Claims claims = JWTUtil.checkJWT(token);
            if (claims==null){
                //未登录
                CommonUtil.sendJsonMessage(response, JsonData.buildError(BizCodeEnum.ACCOUNT_PWD_ERROR.getMessage()));
                return false;
            }
            Long userId = Long.valueOf(claims.get("id").toString());
            String headImg = (String)claims.get("head_img");
            String mail = (String)claims.get("mail");
            String name = (String)claims.get("name");

            LoginUser loginUser = new LoginUser();
            loginUser.setId(userId);
            loginUser.setHeadImg(headImg);
            loginUser.setMail(mail);
            loginUser.setName(name);
            threadLocal.set(loginUser);
            return true;
        }
        CommonUtil.sendJsonMessage(response, JsonData.buildError(BizCodeEnum.ACCOUNT_OUT_LOGIN.getMessage()));
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}

